package com.za.plugin.transfer.func;



import com.za.plugin.pojo.Content;
import com.za.plugin.util.StrUtil;

import java.util.List;

public class SubdateFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {
        return clearSpace(sql).contains("subdate(");
    }

    private String clearSpace(String sql) {
        return sql.replaceAll("subdate\\s*\\(", "subdate(");
    }

    @Override
    public String transfer(String sql) {
        sql = clearSpace(sql).toLowerCase();
        if (sql.contains("subdate(")) {
            int idx = sql.indexOf("subdate("), left = 0;
            StringBuilder sb = new StringBuilder();
            while (idx >= 0) {
                Content expectContent = StrUtil.getExpectContent(sql, idx + 7);
                assert expectContent != null;
                int end = expectContent.getEnd();
                List<String> segment = StrUtil.getSegment(sql, idx + 8, end - 1);
                if (segment.size() >= 2 && segment.get(1).contains("interval")) {
                    String[] arr = segment.get(1).split("\\s+");
                    String timeUnit = arr[2];
                    sb.append(sql, left, idx).append("dateadd(").append(timeUnit).append(",").append("-")
                            .append("("+arr[1]+")").append(",").append(segment.get(0)).append(")");
                } else if (segment.size() >= 2) {
                    sb.append(sql, left, idx).append("dateadd(").append("day").append(",").append("-")
                            .append("("+segment.get(1)+")").append(",").append(segment.get(0)).append(")");
                }
                idx = sql.indexOf("subdate(", idx + 8);
                if (idx == -1) {
                    sb.append(sql.substring(end));
                }
                left = end;
            }
            sql = sb.toString();
        }
        return sql;
    }
}
